#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>

#define LEFT "["
#define RIGHT "]"
#define DELIM " "
//const char* pwd;
char commandline[1024];
char* argv[32];
extern char** environ;

//1.命令行显示
const char* getUsername()
{
  return getenv("USER");
}

const char* getHostname()
{
  return getenv("HOSTNAME");
}

const char* getPwd()
{
  return getenv("PWD");
}

void show()
{
  printf("%s%s@%s %s%s$ ",LEFT,getUsername(),getHostname(),getPwd(),RIGHT);
}

void interact(char* cline, int size)
{
  show();
  fgets(cline,size,stdin);
  cline[strlen(cline) - 1] = '\0';   //直接在输入时就删除换行，仅在分割时删除换行，每次输入还是会多一个换行
}

//2.输入命令分割
void splitCommand(char* cline, char* _argv[])
{
  _argv[0] = strtok(cline,DELIM);
  int i = 1;
  while(_argv[i++] = strtok(NULL,DELIM));
}


//3.命令运行
int excuteCommand(char* _argv[])
{
  pid_t id = fork();
  if(id < 0)
  {
    perror("fork error\n");
  }
  else if(id == 0)
  {
    execvpe(_argv[0],argv,environ);
    exit(0);
  }
  else
  {
    int status = 0;
    while(waitpid(id, &status,0) == 0);
    return status;
  }
}


//4.内建命令
void buildCommand(char* _argv)
{
  if(strcmp(_argv[0], "cd") == 0)
  {
    
  }

}



int main()
{
  while(1)
  {
    interact(commandline,sizeof(commandline));
    splitCommand(commandline, argv);
    excuteCommand(argv);
  }
  return 0;
}

